//
//  Beauty_PicViewController.m
//  项目A
//
//  Created by 林程杰 on 14/12/29.
//  Copyright (c) 2014年 lanou3g.com 蓝鸥科技. All rights reserved.
//

#import "Beauty_PicViewController.h"
#import "AFJSONRequestOperation.h"
#import "UIImageView+WebCache.h"
#import "macro.h"
#import "UIScrollView+MJRefresh.h"
#import "Masonry.h"
#import "WebColor.h"

@implementation Beauty_PicViewController

- (void)dealloc
{
    [_bigView release];
    [_tableArray release];
    [super dealloc];
}

- (instancetype) init
{
    self = [super init];
    if (self) {
        self.tableArray = [NSMutableArray array];
        self.number = 20;
    }
    return self;
}

- (void) viewDidLoad
{
    [super viewDidLoad];
    [self.view setBackgroundColor:[WebColor seaShell]];
    
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(100, 0, 45, 100)];
    label.textColor = [UIColor whiteColor];
    label.backgroundColor = [UIColor clearColor];
    label.font = [UIFont fontWithName:@"TimesNewRomanPS-BoldMT" size:20];
    label.text = @"精美图片";
    self.navigationItem.titleView = label;
    [label release];
    
    UIButton *button = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 25, 25)];
    [button setBackgroundImage:[UIImage imageNamed:@"return.png"] forState:UIControlStateNormal];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:button];
    [button addTarget:self action:@selector(returnBack) forControlEvents:UIControlEventTouchUpInside];
    [button release];
    
    self.imageViews = [[UIImageView alloc] initWithFrame:CGRectMake(self.view.frame.size.width / 2 - 30, self.view.frame.size.height / 2 - 90, 60, 60)];
    _imageViews.image = [UIImage imageNamed:@"fireLogin.png"];
    _imageViews.layer.cornerRadius = 30;
    _imageViews.clipsToBounds = YES;
    [_imageViews setBackgroundColor:[WebColor seaShell]];
    [self.view addSubview:_imageViews];
    
    
    CABasicAnimation* rotationAnimation;
    rotationAnimation = [CABasicAnimation animationWithKeyPath:@"transform.rotation.z"];
    rotationAnimation.toValue = [NSNumber numberWithFloat: M_PI * 2.0 ];
    [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
    rotationAnimation.duration = 2;
    rotationAnimation.RepeatCount = 10000;
    rotationAnimation.cumulative = NO;
    rotationAnimation.removedOnCompletion = NO;
    rotationAnimation.fillMode = kCAFillModeBoth;
    [_imageViews.layer addAnimation:rotationAnimation forKey:@"rotation"];
    [_imageViews release];
    [self connectModel];
    
}

- (void)connectModel
{
    NSString *str = @"http://api.breadtrip.com/featured/photos/?start=0";
    NSURL *url = [NSURL URLWithString:[str stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    AFJSONRequestOperation *operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:request success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) {
        [_imageViews removeFromSuperview];
        NSArray *itemsArray = [JSON objectForKey:@"items"];
        
        [_tableArray removeAllObjects];
        [_tableArray addObjectsFromArray:itemsArray];
        [self creatCollectionView];
        [_collect reloadData];
        [self SetUpRefresh];
    } failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id JSON) {
        NSLog(@"发生错误了!%@", error);
    }];
    [operation start];    
}

- (void) creatCollectionView
{
    UICollectionViewFlowLayout *flow = [[UICollectionViewFlowLayout alloc] init];
    
    self.collect = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height) collectionViewLayout:flow];
    
    flow.scrollDirection = UICollectionViewScrollDirectionVertical;
    flow.itemSize = CGSizeMake(SCREEN_WIDTH / 2 - 9, SCREEN_HEIGHT / 3 - 40);
    
    flow.minimumLineSpacing = 4;
    flow.minimumInteritemSpacing = 4;
    
    flow.sectionInset = UIEdgeInsetsMake(7, 7, 7, 7);
    
    _collect.backgroundColor = [WebColor seaShell];
    
    [_collect registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:@"cell1"];
    
    _collect.dataSource = self;
    _collect.delegate = self;
    [self.view addSubview:_collect];
    
    self.bigView = [[UIView alloc] initWithFrame:CGRectMake(16, self.view.frame.size.height / 6, self.view.frame.size.width - 30, self.view.frame.size.width - 30)];
    [_bigView setBackgroundColor:[UIColor whiteColor]];
    _bigView.layer.cornerRadius = 7;
    _bigView.clipsToBounds = YES;
    _bigView.hidden = YES;
    [self.view addSubview:_bigView];
    
    self.imageView2 = [[UIImageView alloc] initWithFrame:CGRectMake(5, 5, _bigView.frame.size.width - 10, _bigView.frame.size.width - 10)];
    [_bigView addSubview:_imageView2];
    
    UIButton *BigButton = [[UIButton alloc] initWithFrame:CGRectMake(5, 5, _bigView.frame.size.width - 10, _bigView.frame.size.width - 10)];
    [BigButton addTarget:self action:@selector(hiddenView :) forControlEvents:UIControlEventTouchUpInside];
    [_bigView  addSubview:BigButton];

    [_bigView release];
    [_collect release];
    [BigButton release];
    [flow release];
    
}


- (NSInteger) collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return [_tableArray count];
}

- (UICollectionViewCell *) collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"cell1" forIndexPath:indexPath];
    
    NSDictionary *dicItems = [_tableArray objectAtIndex:indexPath.item];
    
    
    NSString *province = [dicItems objectForKey:@"province"];
   
    UIButton *button = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH / 2 - 9, SCREEN_HEIGHT / 3 - 40)];

    self.imageView = [[UIImageView alloc] initWithFrame:CGRectMake(5, 5, _bigView.frame.size.width - 10, _bigView.frame.size.width - 10)];
    _imageView.layer.cornerRadius = 6;
    _imageView.layer.masksToBounds = YES;
    
    [_imageView sd_setImageWithURL:[NSURL URLWithString:[dicItems objectForKey:@"photo_w640"]] placeholderImage:[UIImage imageNamed:@"zhanwei.png"]];
    
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(SCREEN_WIDTH / 2 - 100, SCREEN_HEIGHT / 3 - 70, 110, 30)];

    label.font = [UIFont systemFontOfSize:15];
    label.highlighted = YES;
    label.textColor = [UIColor whiteColor];
    label.backgroundColor = [UIColor clearColor];
    [label setText:province];
    [button addSubview:label];
    [cell setBackgroundView:_imageView];
    [_imageView addSubview:label];

    [button release];
    [label release];
    [_imageView release];
   
    
    return cell;
}

- (void) collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    _bigView.hidden = NO;

    NSDictionary *dicItems = [_tableArray objectAtIndex:indexPath.item];
//    self.imageView2 = [[UIImageView alloc] initWithFrame:CGRectMake(5, 5, _bigView.frame.size.width - 10, _bigView.frame.size.width - 10)];
    [_imageView2 sd_setImageWithURL:[NSURL URLWithString:[dicItems objectForKey:@"photo_w640"]] placeholderImage:[UIImage imageNamed:@"zhanwei.png"]];
//    [_bigView addSubview:_imageView2];

}

- (void) hiddenView : (id) sender
{
    _bigView.hidden = YES;
}


- (void)SetUpRefresh
{
    // 1.下拉刷新(进入刷新状态就会调用self的headerRereshing)
    [self.collect addHeaderWithTarget:self action:@selector(downLoad)];
    // #warning 自动刷新(一进入程序就下拉刷新)
    [self.collect headerBeginRefreshing];
    
    //2.上拉加载更多(进入刷新状态就会调用self的footerRereshing)
    if ([self.tableArray count] < 100) {
        [self.collect addFooterWithTarget:self action:@selector(upLoad)];
    }
    
    // 设置文字(也可以不设置,默认的文字在MJRefreshConst中修改)
    self.collect.headerPullToRefreshText = @"下拉可以刷新了";
    self.collect.headerReleaseToRefreshText = @"松开立即刷新了";
    self.collect.headerRefreshingText = @"正在刷新中";
    
    self.collect.footerPullToRefreshText = @"上拉可以加载更多数据了";
    self.collect.footerReleaseToRefreshText = @"松开立即加载更多数据";
    self.collect.footerRefreshingText = @"正在加载中";
}


- (void) downLoad
{
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        // 刷新表格
        
        [self.collect reloadData];
        
        // (最好在刷新表格后调用)调用endRefreshing可以结束刷新状态
        [self.collect headerEndRefreshing];
    });

}


- (void) upLoad
{
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        // 刷新表格
        _number += 20;
        NSString *str = @"http://api.breadtrip.com/featured/photos/?start=";
        str = [NSString stringWithFormat:@"http://api.breadtrip.com/featured/photos/?start=%ld", (long)_number - 20];
        [self json:str];
        // (最好在刷新表格后调用)调用endRefreshing可以结束刷新状态
        [self.collect footerEndRefreshing];
    });  
}

- (void)json:(NSString *)str
{
    NSURL *url = [NSURL URLWithString:[str stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    AFJSONRequestOperation *operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:request success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) {
        NSArray *itemsArray = [JSON objectForKey:@"items"];
        [_tableArray addObjectsFromArray:itemsArray ];
        [_collect reloadData];
    } failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id JSON) {
        NSLog(@"发生错误%@", error);
    }];
    [operation start];
}

- (void) returnBack
{
    [self.navigationController popToRootViewControllerAnimated:YES];
}


@end
